package com.liycloud.gateway.handler;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liycloud.common.core.util.ResultVo;
import com.liycloud.common.gateway.support.RouteCacheHolder;
import com.liycloud.common.gateway.vo.RouteDefinitionVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ReactiveHttpOutputMessage;
import org.springframework.stereotype.Component;

import org.springframework.web.reactive.function.BodyInserter;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;

import reactor.core.publisher.Mono;

import java.util.List;


/**
 *  查询路由配置信息的 Endpoint
 *
 */
@Slf4j
@Component
@AllArgsConstructor
public class GatewayRouterEndpointHandler implements HandlerFunction<ServerResponse> {

	private final ObjectMapper objectMapper;

	@Override
	public Mono<ServerResponse> handle(ServerRequest request) {

		// 从 内存缓存 获取
		List<RouteDefinitionVo> routeList = RouteCacheHolder.getRouteList();

		try {
			BodyInserter<String, ReactiveHttpOutputMessage> bodyInserter = BodyInserters.fromValue(objectMapper.writeValueAsString(ResultVo.ok(routeList,"网关路由信息")));
			Mono<ServerResponse> responseMono = ServerResponse
					.status(HttpStatus.OK)
					.contentType(MediaType.APPLICATION_JSON)
					.body(bodyInserter);
			return responseMono;
		} catch (JsonProcessingException e) {
			log.error("查询网关路由配置信息失败 !");
			e.printStackTrace();
		}
		return null;
	}
}
